---
title: Summary of conservation gap analysis
output:
  html_document:
highlight: tango
theme: yeti
toc: no
toc_depth: 4
toc_float:
  collapsed: yes
smooth_scroll: no
---

```{r echo=FALSE, message=FALSE, warning=FALSE}
suppressWarnings(suppressMessages(require(tmap)))
tmap::tmap_mode("view")
```

```{r echo=FALSE, message=FALSE, warning=FALSE}
#Checking Occurrence_data format
  par_names <- c("species","latitude","longitude","type")

  if(identical(names(Od),par_names)==FALSE){
    stop("Please format the column names in your dataframe as species,latitude,longitude,type")
  }
  #Checking if user is using a raster list or a raster stack
  if(class(Rl)=="RasterStack"){
    Rl <- raster::unstack(Rl)
  } else {
    Rl <- Rl
  }

  # Load in protected areas

  if(is.null(Pro_areas) | missing(Pro_areas)){
    if(file.exists(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis"))){
      Pro_areas <- raster::raster(system.file("data/preloaded_data/protectedArea/wdpa_reclass.tif",package = "GapAnalysis"))
    } else {
      stop("Protected areas file is not available yet. Please run the function GetDatasets()  and try again")
    }
  } else{
    Pro_areas <- Pro_areas
  }
  
    # load in ecoregions dataset
  # Load in ecoregions shp
  #print(missing(Ecoregions_shp))
  if(is.null(Ecoregions_shp)){
    if(file.exists(system.file("data/preloaded_data/ecoRegion/tnc_terr_ecoregions.shp",package = "GapAnalysis"))){
      Ecoregions_shp <- raster::shapefile(system.file("data/preloaded_data/ecoRegion/tnc_terr_ecoregions.shp", package = "GapAnalysis"),encoding = "UTF-8")
    } else {
      stop("Ecoregions file is not available yet. Please run the function GetDatasets() and try again")
    }
  } else{
    Ecoregions_shp <- Ecoregions_shp
  }


round_df <- function(x, digits) {
    # round all numeric variables
    # x: data frame 
    # digits: number of digits to round
    numeric_columns <- sapply(x, mode) == 'numeric'
    x[numeric_columns] <-  round(x[numeric_columns], digits)
    x
}

## palettes 
# Palette options 
hPColor <- "#1184D4"
gPColor <- "#6300F0"
binaryPal <- c( "#FFFFFF","#45B320") # white, green 
ersBPal <- c(  "#FFFFFF", "#7570b3") # white, purple
gBufPal <- c(  "#FFFFFF","#45B320","#7570b3") # white , green, purple 
ecoPal <- "RdYlBu" # https://colorbrewer2.org/#type=diverging&scheme=RdBu&n=3
proPal <- "#7570b3" # same color as val 2 in gBufPal 
srsinPal <- c("#FFFFFF", "#FA4101") # white to red 


```

```{r echo=FALSE, message=FALSE, warning=FALSE, } 
# redeclare inputs for ease of entering in values for all functions 

#insitu
inSRS <- GapAnalysis::SRSin(Species_list = Sl, Occurrence_data = Od, 
                            Raster_list = Rl, Pro_areas = Pro_areas, Gap_Map = TRUE)

inGRS <- GapAnalysis::GRSin(Species_list = Sl, Occurrence_data = Od, 
                            Raster_list = Rl, Pro_areas = Pro_areas, 
                            Gap_Map = TRUE)

inERS <- GapAnalysis::ERSin(Species_list = Sl, Occurrence_data = Od, 
                            Raster_list = Rl, Pro_areas = Pro_areas, Ecoregions_shp = Ecoregions_shp,
                            Gap_Map = TRUE)

inFCS <- GapAnalysis::FCSin(Species_list = Sl, Occurrence_data = Od, 
                            Raster_list = Rl, Pro_areas = Pro_areas, Ecoregions_shp = Ecoregions_shp)
                           


# exsitu 
exSRS <- GapAnalysis::SRSex(Species_list = Sl, Occurrence_data = Od)

exGRS <- GapAnalysis::GRSex(Occurrence_data = Od, Species_list = Sl,
                            Buffer_distance = Buffer_distance,
                            Raster_list = Rl, Gap_Map = TRUE)

exERS <- GapAnalysis::ERSex(Species_list = Sl, Occurrence_data = Od,
                            Buffer_distance = Buffer_distance, 
                            Raster_list = Rl,Ecoregions_shp = Ecoregions_shp, 
                            Gap_Map = TRUE )

exFCS <- GapAnalysis::FCSex(Species_list = Sl,Occurrence_data = Od,
                            Buffer_distance = Buffer_distance,
                            Raster_list = Rl, Ecoregions_shp = Ecoregions_shp)

#summary
fcsMean <- GapAnalysis::FCSc_mean(FCSex_df = exFCS, FCSin_df = inFCS)

```

<br>

### Summary of occurrences 



```{r  echo=FALSE, message=FALSE, warning=FALSE}
ocCount <- GapAnalysis::OccurrenceCounts(species = Sl[1],Occurrence_data = Od)
ocCount <- round_df(ocCount, 4)
if(length(Sl)>1){
  for(i in 2:length(Sl)){
o <- GapAnalysis::OccurrenceCounts(species = Sl[i],Occurrence_data = Od)
o <- round_df(o, 4)
ocCount <- rbind(ocCount, o)
  }
}
nam1 <- colnames(ocCount)
colnames(ocCount) <- c("species", nam1[c(2:length(nam1))])
t1<- knitr::kable(x = ocCount)
kableExtra::kable_styling(kable_input = t1, bootstrap_options = "striped", full_width = F)
```

Taxon: The species of interest. 

totalRecords: Number of occurrences associated with the taxon. 

hasLat:Number of occurrences with valid latitude value. 

hasLong: Number of occurrences with valid longitude value. 

totalCoords: Number of occurrences with valid latitude and longitude.  

totalGRecords: Number of ex situ conservation (genebanks and botanical gardens) occurrences.

totalGCoords: Number of ex situ conservation occurrences with valid latitude and longitude. 

totalHRecords: Number of reference (herbarium) occurrences.

totalHCoords: Number of reference occurrences with valid latitude and longitude.  


<br>
<br>


```{r  echo=FALSE, message=FALSE, warning=FALSE}
# develop ex situ data summary 
exsituSummary <- data.frame(matrix(nrow = 1, ncol = 6))
colnames(exsituSummary) <- c("species", "SRSex", "GRSex", "ERSex","FCSex", "FCSex_class")
exsituSummary[1,] <- exFCS[1,]
```

<br>

### Ex situ conservation gap analysis

The table below shows the ex situ conservation gap analysis summary results. The SRSex process assesses the completeness of ex situ conservation collections, calculating the ratio of germplasm accessions (G) available in ex situ repositories to reference (H) records for each taxon, making use of all compiled records, regardless of whether they include coordinates, with an ideal (i.e., comprehensive) conservation ratio of 1:1. The GRSex process provides a geographic measurement of the proportion of a species’ range that can be considered to be conserved in ex situ repositories. The ERSex process provides an ecological measurement of the proportion of a species range that can be considered to be conserved in ex situ repositories. 
All scores are bound between 0 and 100, with 0 representing an extremely poor state of conservation, and 100 representing comprehensive protection. The final ex situ conservation score is called FCSex and is a mean of the three ex situ conservation scores. The FCSex is used to categorize species, with high priority (HP) for further conservation action assigned when FCSex < 25, medium priority (MP) where 25 ≤ FCSex < 50, low priority (LP) where 50 ≤ FCSex < 75, and sufficiently conserved (SC) for taxa whose FCSex ≥75.

```{r echo=FALSE, message=FALSE, warning=FALSE}
exsituSummary <- round_df(exsituSummary, 4)
t2<- knitr::kable(x = exsituSummary)
kableExtra::kable_styling(kable_input = t2, bootstrap_options = "striped", full_width = F)
```

<br>
<br>
<br>

#### Map of ex situ geographical representativeness (GRSex)
Map of the potential distribution, with previous germplasm collection points surrounded by a 50 km buffer overlaid. Only germplasm points are displayed on the map.

Native area (ecoregions within countries where species has been observed in the field) = 0

Potential distribution not conserved ex situ = 1

Potential distribution conserved ex situ (within G buffer) = 2

```{r  echo=FALSE, message=FALSE, warning=FALSE}
r1 <- Rl[[1]]
r2 <- r1
r2[r2==1]<-2

g1 <- exGRS$gap_maps[[1]]
g1[is.na(g1),] <- 0
g2 <- r2 - g1

gd <- Od[Od$type == "G",]
gd <- gd[!is.na(gd$latitude),]

if(nrow(gd) >0 ){
  gp <- sp::SpatialPoints(coords = gd[,c(3,2)],proj4string = crs(r1))

tm_shape(g2, name = "Native area, distribution model, and G buffers")+
  tm_raster(style="cat", title = "Map of GRSex",palette = gBufPal, 
            labels = c("0: Native area", 
                       "1: Potential distribution not conserved ex situ",
                       "2: Potential distribution conserved ex situ"))+
  tm_shape(gp, name = "G occurrences")+
    tm_dots(col = gPColor,title = "Germplasma Occurrences",legend.show = TRUE)
}else{
   tm_shape(g2, name = "Native area and distribution model")+
  tm_raster(style="cat", title = "Map of GRSex",palette = gBufPal,
            labels = c("0: Native area",
                       "1: Potential distribution not conserved ex situ",
                       "2: Potential distribution conserved ex situ"))
}


# 
#     if(1 %in% unique(values(comb2))){
#           tm_shape(comb2, name = "Native area, distribution model, and G buffers") +
#       tm_raster(palette = gBufPal, style = "cat",
#                 title = paste0("GRSex of ", species))+
#     tm_shape(gPoint, name = "G occurrences") + tm_dots(col = gPColor)+
#       tm_scale_bar()
#     }else{
#     tm_shape(comb2, name = "Native area, distribution model, and G buffers") +
#       tm_raster(palette = gBinary, style = "cat",
#                 title = paste0("GRSex of ", species))+
#     tm_shape(gPoint, name = "G occurrences") + tm_dots(col = gPColor)+
#       tm_scale_bar()
#     }
# 


```

<br>
<br>
<br>

#### Map of ex situ ecological representativeness (ERSex)

Map of the potential distribution, with ecoregions from which no G occurrences points have been collected. 

Native area (ecoregions within countries where species has been observed in the field) = 0

Potential distribution where ecoregions have been conserved ex situ = 1

Potential distribution where ecoregions have not been conserved ex situ, labeling the ecoregions = >1 


```{r  echo=FALSE, message=FALSE, warning=FALSE}
g1 <- exERS$gap_maps[[1]]
gEco <- unique(raster::values(g1))

# mask  based on predicted presence area
r2 <- r1
r2[r2 == 0]<-NA

e1 <- Ecoregions_shp[Ecoregions_shp$ECO_ID_U %in% gEco,]
#convert to sf object for conversion using fasterize
e1 <- sf::st_as_sf(e1, r1)
# generate a ecoregion raster keeping the unique id.
e1 <- fasterize::fasterize(e1, r1, field = "ECO_ID_U")
e1 <- e1 * r2 


if(length(gEco) > 30){
  tm_shape(r1, name = "Native area and distribution model")+
    tm_raster(palette = ersBPal, style = "cat",title = paste0("Map of ERSex"),
              labels = c("0: Native area", "1: Potential distribution where ecoregions conserved ex situ"))+
  tm_shape(e1, name = "Ecoregions not conserved ex situ") +
    tm_raster(palette = ecoPal, style ="pretty", title = "Ecoregions not conserved ex situ") 
  }else{
  tm_shape(r1, name = "Native area and distribution model")+
    tm_raster(palette = ersBPal, style = "cat",title = paste0("Map of ERSex"),
              labels = c("0: Native area", "1: Potential distribution where ecoregions conserved ex situ"))+
  tm_shape(e1, name = "Ecoregions not conserved ex situ") +
    tm_raster(palette = ecoPal, style ="cat", title = "Ecoregions not conserved ex situ") 
  }
  
  
```

<br>
<br>

This table shows the descriptions of the ecoregions within the potential distribution, with regard to ex situ conservation 
```{r  echo=FALSE, message=FALSE, warning=FALSE}
# extract all ecoregions form 

predictedPresence <- sp::SpatialPoints(raster::rasterToPoints(r1))
suppressWarnings(raster::crs(predictedPresence) <- raster::crs(Ecoregions_shp))
ecoVals <- suppressWarnings(sp::over(x = predictedPresence, y = Ecoregions_shp))
ecoVals <- data.frame(ECO_ID_U=(unique(ecoVals$ECO_ID_U)))
ecoVals <- ecoVals[which(!is.na(ecoVals) & ecoVals>0),]

gEco <- gEco[!is.na(gEco)]
if(length(gEco)>0){
  allEco <- Ecoregions_shp@data[Ecoregions_shp@data$ECO_ID_U %in% ecoVals, ]
  allEco <- allEco[which(!duplicated(allEco)),]
  allEco$`Conserved Ex Situ` <- NA
  for(i in 1:nrow(allEco)){
    if(allEco$ECO_ID_U[i] %in% gEco){
      allEco$`Conserved Ex Situ`[i] <- "Not Conserved"
    }else{
      allEco$`Conserved Ex Situ`[i] <- "Conserved"
    }
  }
  
}

allEco <- allEco[,c("ECO_ID_U", "ECO_NAME","Conserved Ex Situ", "WWF_MHTNAM" ,"SOURCEDATA")]

DT::datatable(allEco,rownames = FALSE)
```

ECO_ID_U: Unique value representing the ecoregion on the map. 

ECO_NAME: The name of the ecoregion. 

Conserved Ex Situ: Whether occurrences have been collected within this ecoregion for ex situ conservation.

ECODE_NAME: The eco_code and name of the ecoregion. 

WWF_REALM2: The World Wildlife Foundation Realm. A more generalized category of ecoregion. 

SOURCEDATA: The citation of the ecoregion definition. 


<br>
<br>
<br>


### In situ conservation gap analysis

```{r  echo=FALSE, message=FALSE, warning=FALSE}
# develop ex situ data summary 
insituSummary <- data.frame(matrix(nrow = 1, ncol = 6))
colnames(insituSummary) <- c("species", "SRSin", "GRSin", "ERSin","FCSin","FCSin_class")
insituSummary[1,] <- inFCS[1,]
```

The table below shows the in situ conservation gap analysis summary.  SRSin reports the proportion of occurrences which fall within protected areas (WDPA database 2019). The GRSin process provides a geographic measurement of the proportion of a species’ range that can be considered to be conserved in protected areas. The ERSin process provides an ecological measurement of the proportion of a species range that can be considered to be conserved in protected areas.  
All scores are bound between 0 and 100, with 0 representing an extremely poor state of conservation, and 100 representing comprehensive protection. The final in situ conservation score is called FCSin and is a mean of the three in situ conservation scores. The FCSin is used to categorize species, with high priority (HP) for further conservation action assigned when FCSin < 25, medium priority (MP) where 25 ≤ FCSin < 50, low priority (LP) where 50 ≤ FCSin < 75, and sufficiently conserved (SC) for taxa whose FCSin ≥75.

```{r echo=FALSE, message=FALSE, warning=FALSE}
insituSummary <- round_df(insituSummary, 4)
t3 <- knitr::kable(x = insituSummary)
  
kableExtra::kable_styling(kable_input = t3, bootstrap_options = "striped", full_width = F)
  
```
<br>
<br>
<br>

#### Map of in situ sampling representativeness (SRSin) 
Map of occurrences within the predicted distribution that are outside of protected areas. Values are summarized by count per cell. 


Predicted distribution = 0

Number of occurrences present at location outside of a protected area = 1 and above 

Protected areas are displayed in purple

```{r  echo=FALSE, message=FALSE, warning=FALSE}
g1 <- inSRS$gap_maps[[1]]
Pro_areas <- raster::crop(x = Pro_areas, y = r1)
Pro_areas <- raster::resample(x = Pro_areas, y = r1,method = "ngb")
p1 <- r1 *Pro_areas
p1[p1 == 0]<-NA

tm_shape(g1, name = "Density of occurrences outside protected areas")+
  tm_raster(style = "cat",palette = srsinPal, title = "Number of occurrences outside of protected areas") +
  tm_shape(p1, name = "Protected areas")+
    tm_raster(palette = proPal, title = "Protected areas", 
              labels = " ")

```
<br>
<br>
<br>

#### Map of in situ geographical representativeness (GRSin)

Map of the potential distribution, with distribution occurring within existing protected areas (WDPA 2019) highlighted.

Native area (ecoregions within countries where species has been observed in the field) = 0

Predicted distribution outside of protected areas = 1

Predicted distribution falling within protected areas = 2

```{r  echo=FALSE, message=FALSE, warning=FALSE}
r1 <- Rl[[1]]
p1[is.na(p1)]<-0
g2 <- r1 + p1

tm_shape(g2, name = "Native area, distribution model, and protected areas")+
  tm_raster(style = "cat", palette = gBufPal,
            title = "Map of GRSin", 
            labels = c("0: Native area", 
                       "1: Potential distribution outside protected areas",
                       "2: Potential distribution falling within protected areas"))
```
<br>
<br>
<br>

#### Map of in situ ecological representativeness (ERSin)

Map of the potential distribution, with ecoregions from which no protected areas are present 

Native area (ecoregions within countries where species has been observed in the field) = 0

Potential distribution where ecoregions have been conserved in situ = 1

Potential distribution where ecoregions have not been conserved in situ, labeling the ecoregions = >1


```{r  echo=FALSE, message=FALSE, warning=FALSE}
g1 <- inERS$gap_maps[[1]]
gEco <- unique(raster::values(g1))
g1[g1 ==0] <- NA

if(length(gEco)>30){
  try(tm_shape(r1, name = "Native area and distribution model where ecoregions conserved in situ")+
  tm_raster(style = "pretty", palette = ersBPal, title = "Map of ERSin",
            labels = c("0: Native area", "1: Potential distribution where ecoregions conserved in situ"))+
tm_shape(g1, name = "Ecoregions not conserved in situ")+
  tm_raster(style = "cat", palette = ecoPal, title = "Ecoregions not conserved in situ"))
}else{
  try(tm_shape(r1, name = "Native area and distribution model where ecoregions conserved in situ")+
  tm_raster(style = "cat", palette = ersBPal, title = "Map of ERSin",
            labels = c("0: Native area", "1: Potential distribution where ecoregions conserved in situ"))+
tm_shape(g1, name = "Ecoregions not conserved in situ")+
  tm_raster(style = "cat", palette = ecoPal, title = "Ecoregions not conserved in situ"))
}


```

<br>
<br>

This table shows the descriptions of the ecoregions within the potential distribution, with regard to in situ conservation

```{r  echo=FALSE, message=FALSE, warning=FALSE}
gEco <- gEco[!is.na(gEco)]

if(length(gEco)>0){
  allEco <- Ecoregions_shp@data[Ecoregions_shp@data$ECO_ID_U %in% ecoVals, ]
  allEco <- allEco[which(!duplicated(allEco)),]

  allEco$`Conserved In Situ` <- ifelse(test = allEco$ECO_ID_U %in% gEco,
                                       yes = "Not Conserved",
                                       no = "Conserved")

  
  allEco <- allEco[,c("ECO_ID_U", "ECO_NAME","Conserved In Situ", "WWF_MHTNAM" ,"SOURCEDATA")]


}
DT::datatable(allEco,rownames = FALSE)
```


ECO_ID_U: Unique value representing the ecoregion on the map. 

ECO_NAME: The name of the ecoregion. 

Conserved In Situ: Whether this ecoregion occurs within protected areas.

ECODE_NAME: The eco_code and name of the ecoregion. 

WWF_REALM2: The World Wildlife Foundation Realm. A more generalized category of ecoregion. 

SOURCEDATA: The citation of the ecoregion definition. 

<br>
<br>
<br>
<br>
<br>

#### Combined conservation gap analysis 

This table shows the combined ex situ and in situ conservation gap analysis metrics. FCSc-mean is the final combined conservation score, and is the average of the FCSex and FCSin. The species is categorized with regard to the min and max between the ex situ and in situ conservation scores, and the combined score, with high priority (HP) for further conservation action assigned when FCS < 25, medium priority (MP) where 25 ≤ FCS < 50, low priority (LP) where 50 ≤ FCS < 75, and sufficiently conserved (SC) for taxa whose FCS ≥75.

```{r  echo=FALSE, message=FALSE, warning=FALSE}
fcsMean <- round_df(fcsMean, 4)
t4 <- knitr::kable(x = fcsMean)
kableExtra::kable_styling(kable_input = t4, bootstrap_options = "striped", full_width = F)
  
```



<br>
<br>
<br>



